package com.lightChat.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * 处理http请求
 * @author sxt
 * @create 2019-11-13 21:00
 */
public class CustomHandler extends SimpleChannelInboundHandler<HttpObject> {




    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {

        Channel channel = channelHandlerContext.channel();
        if(httpObject instanceof HttpRequest){
            System.out.println("远程客户端地址是：" + channel.remoteAddress());
        }



        //。。。。。。。。。。。。。。。。执行了一些业务逻辑

        //给客户端响应自定义的内容
        ByteBuf context = Unpooled.copiedBuffer("Heelo,Netty", CharsetUtil.UTF_8);

        //创建响应对象（封装响应信息）
        DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1, HttpResponseStatus.OK,context);

        HttpHeaders headers = defaultFullHttpResponse.headers();
        headers.set(HttpHeaderNames.CONTENT_TYPE,"text/plain");//设置响应文本类型
        headers.set(HttpHeaderNames.CONTENT_LENGTH,context.readableBytes());//设置响应文本的长度


        channel.writeAndFlush(defaultFullHttpResponse);//实际意义上的响应

    }


    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        ChannelId id = channel.id();
        System.out.println("新的channel加入：" + id);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        ChannelId id = channel.id();
        System.out.println(id + " 连接断开");


    }
}
